﻿using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2023-06-21 15:32
    /// 描 述：工况表
    /// </summary>
    public class ec_CaseService
    {
        #region 仓储
        Repository<ec_CaseEntity> _caseRepository => new Repository<ec_CaseEntity>();
        #endregion
        #region 提交数据

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, ref string keyValue, ec_CaseEntity entity)
        {
            try
            {
                string tableName = ProjectSugar.TableName<ec_CaseEntity>(ProjectId);
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    _caseRepository.AsUpdateable(entity).AS(tableName).ExecuteCommand();
                }
                else
                {
                    entity.Create();
                    _caseRepository.AsInsertable(entity).AS(tableName).ExecuteCommand();
                    keyValue = entity.CaseID;

                    //只创建时添加工程数据属性
                    //所有的property都要同步加
                    //查出所有的对象类型（ec_objectType），遍历
                    //查出每个对象类型里的属性（ec_objectTypeP)
                    //查出每个对象类型里的位号（ec_enginedata)，遍历
                    //每个位号都插入一套属性（ec_enginedata_property）
                    var propertyTableName = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);
                    var objecttypepTableName = ProjectSugar.TableName<ec_objecttypepEntity>(ProjectId);
                    var objecttypeTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                    var unitTableName = ProjectSugar.TableName<ec_measuring_unitEntity>(ProjectId);
                    var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                    var enginedataPropTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);

                    var enginedataProps = new List<ec_enginedata_propertyEntity>();
                    string CaseID = keyValue;
                    SqlSugarHelper.Db.Queryable<ec_propertyEntity>().AS(propertyTableName)
                        .InnerJoin<ec_objecttypepEntity>((a, b) => a.PropertyID == b.PropertyID)
                        .AS<ec_objecttypepEntity>(objecttypepTableName)
                        .InnerJoin<ec_objecttypeEntity>((a, b, c) => b.ObjectTypeID == c.ObjectTypeID)
                        .AS<ec_objecttypeEntity>(objecttypeTableName)
                        .InnerJoin<ec_enginedataEntity>((a, b, c, d) => b.ObjectTypeID == d.ObjectTypeID)
                        .AS<ec_enginedataEntity>(enginedataTableName)
                        .LeftJoin<ec_measuring_unitEntity>((a, b, c, d, e) => a.DefaultUnit == e.MeasuringUnitID)
                        .AS<ec_measuring_unitEntity>(unitTableName)
                        .Select((a, b, c, d, e) => new { a, d, e })
                        .ToList().ForEach(x =>
                        {
                            var enginedataProp = new ec_enginedata_propertyEntity()
                            {
                                EngineDataID = x.d.EngineDataID,
                                PropertyName = x.a.PropertyName,
                                PropertyValue = x.a.DefaultValue,
                                MeasuringUnit = x.e.MeasuringUnitName,
                                CaseID = CaseID,
                            };
                            enginedataProp.Create();
                            enginedataProps.Add(enginedataProp);
                        });
                    SqlSugarHelper.Db.Fastest<ec_enginedata_propertyEntity>().AS(enginedataPropTableName).BulkCopy(enginedataProps);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var tableName = ProjectSugar.TableName<ec_CaseEntity>(ProjectId);
                _caseRepository.AsDeleteable().AS(tableName).Where(x => x.CaseID == keyValue).ExecuteCommand();

                //同时删掉对应一批的ec enginedata property，需要在插件端再三确认
                //移动到Service,有事务控制
                Repository<ec_enginedata_propertyEntity> propertyRepo = new Repository<ec_enginedata_propertyEntity>();
                var propertyTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);
                Repository<ec_enginedata_propertyhisEntity> hisRepo = new Repository<ec_enginedata_propertyhisEntity>();
                var propertyHisTableName = ProjectSugar.TableName<ec_enginedata_propertyhisEntity>(ProjectId);
                propertyRepo.AsDeleteable().Where(t => t.CaseID == keyValue).AS(propertyTableName).ExecuteCommand();
                hisRepo.AsDeleteable().Where(t => t.CaseID == keyValue).AS(propertyHisTableName).ExecuteCommand();

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion
    }
}
